package com.yc.jpyy.studentbase.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.util.PageBean;
import com.yc.jpyy.studentbase.service.StudentBaseService;
import com.yc.jpyy.utils.Tools;




@Controller
@RequestMapping(value = "/studentbase")
@Scope("prototype")
public class StudentBaseController extends BaseController {
	
	@Autowired
	private StudentBaseService studentBaseService;
    private static Logger logger = LoggerFactory.getLogger(StudentBaseController.class);
	
    //新增
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addStudentBase", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addStudentBase(HttpServletRequest request) throws UnsupportedEncodingException {
		
		RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		
		try{
			String info = request.getParameter("info");
			System.out.println("info"+info);
			//设置数据源
			Map<String,Object> paramsMap = Tools.JsonToMap(info);
			System.out.println("paramsMap"+paramsMap);
			String dbcode = paramsMap.get("dbcode").toString();
		    HandlerDataSource.setDataSource(dbcode);
		    studentBaseService.addStudentBaseService(paramsMap);
			logger.info("新增二保成功");
			response.setReturnMsg(1, "操作成功");
			return response.toJSON();
			
		} catch (Exception e) {
			logger.error("新增二保成功处理异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}
		
		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
		
	}
	
	
	
	//修改
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateStudentBase", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateStudentBase(HttpServletRequest request) throws UnsupportedEncodingException {
		
		RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		
		try{
			String info = request.getParameter("info");
			System.out.println(info);
			Map<String,Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			//设置数据源
		    HandlerDataSource.setDataSource(dbcode);
		    studentBaseService.updateStudentBaseService(paramsMap);
			response.setReturnMsg(1, "操作成功");
			return response.toJSON();
			
		} catch (Exception e) {
			logger.info("修改违章处理异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			e.printStackTrace();
		}
		
		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
		
	}
	
	//查询所有
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findStudentBase", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findStudentBase(HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info"+info);
			Map<String,Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			//设置数据源
			HandlerDataSource.setDataSource(dbcode);
			PageBean pageBean = studentBaseService.findStudentBaseService(paramsMap);
			response.setReturnMsg(1, "操作成功");
            response.setTotalCount(pageBean.getAllRow());
            response.setTotalPage(pageBean.getTotalPage());
			response.setListData(pageBean.getList());
			return response.toJSON();
            
		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}
	
	
	//查询所有 主子表
		@SuppressWarnings("finally")
		@RequestMapping(value = "/findStudentBaseToDetil", method = { RequestMethod.GET,
				RequestMethod.POST }, produces = "application/json; charset=utf-8")
		public @ResponseBody String findStudentBaseToDetil(HttpServletRequest request) throws UnsupportedEncodingException {

			RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
			request.setCharacterEncoding("UTF-8");
			try {
				String info = request.getParameter("info");
				System.out.println("info"+info);
				Map<String,Object> paramsMap = Tools.JsonToMap(info);
				String dbcode = paramsMap.get("dbcode").toString();
				//设置数据源
				HandlerDataSource.setDataSource(dbcode);
			    List<Map<String, Object>> list = studentBaseService.findStudentBaseToDetilService(paramsMap);
	            response.setReturnMsg(1, "操作成功");
	            response.setListData(list);
				return response.toJSON();
	            
			} catch (Exception e) {
				logger.error("findCompany" + e.toString());
				response.setReturnCode(1);
				response.setReturnMsg("查询失败");
				response.setReturnException(e.toString());
			} finally {
				HandlerDataSource.clear();
				return response.toJSON();
			}
		}
	
		//查询所有 主子表 学生表与学生考试表关联
				@SuppressWarnings("finally")
				@RequestMapping(value = "/findStudentBaseToExamResult", method = { RequestMethod.GET,
						RequestMethod.POST }, produces = "application/json; charset=utf-8")
				public @ResponseBody String findProfessionCourses(HttpServletRequest request) throws UnsupportedEncodingException {

					RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
					request.setCharacterEncoding("UTF-8");
					try {
						String info = request.getParameter("info");
						System.out.println("info"+info);
						Map<String,Object> paramsMap = Tools.JsonToMap(info);
						String dbcode = paramsMap.get("dbcode").toString();
						//设置数据源
						HandlerDataSource.setDataSource(dbcode);
						PageBean pageBean = studentBaseService.findStudentBaseToExamResultService(paramsMap);
						response.setReturnMsg(1, "操作成功");
			            response.setTotalCount(pageBean.getAllRow());
			            response.setTotalPage(pageBean.getTotalPage());
						response.setListData(pageBean.getList());
						return response.toJSON();
			            
					} catch (Exception e) {
						logger.error("findCompany" + e.toString());
						response.setReturnCode(1);
						response.setReturnMsg("查询失败");
						response.setReturnException(e.toString());
					} finally {
						HandlerDataSource.clear();
						return response.toJSON();
					}
				}
				
				//查询考试
				@SuppressWarnings("finally")
				@RequestMapping(value = "/findExamResult", method = { RequestMethod.GET,
						RequestMethod.POST }, produces = "application/json; charset=utf-8")
				public @ResponseBody String findExamResult(HttpServletRequest request) throws UnsupportedEncodingException {

					RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
					request.setCharacterEncoding("UTF-8");
					try {
						String info = request.getParameter("info");
						System.out.println("info"+info);
						Map<String,Object> paramsMap = Tools.JsonToMap(info);
						String dbcode = paramsMap.get("dbcode").toString();
						//设置数据源
						HandlerDataSource.setDataSource(dbcode);
					    List<Map<String, Object>> list = studentBaseService.findExamResultService(paramsMap);
			            response.setReturnMsg(1, "操作成功");
			            response.setListData(list);
						return response.toJSON();
			            
					} catch (Exception e) {
						logger.error("findCompany" + e.toString());
						response.setReturnCode(1);
						response.setReturnMsg("查询失败");
						response.setReturnException(e.toString());
					} finally {
						HandlerDataSource.clear();
						return response.toJSON();
					}
				}
		
				
				//查询考试
				@SuppressWarnings("finally")
				@RequestMapping(value = "/findStudentAnswerTest", method = { RequestMethod.GET,
						RequestMethod.POST }, produces = "application/json; charset=utf-8")
				public @ResponseBody String findStudentAnswerTest(HttpServletRequest request) throws UnsupportedEncodingException {

					RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
					request.setCharacterEncoding("UTF-8");
					try {
						String info = request.getParameter("info");
						System.out.println("info"+info);
						Map<String,Object> paramsMap = Tools.JsonToMap(info);
						String dbcode = paramsMap.get("dbcode").toString();
						//设置数据源
						HandlerDataSource.setDataSource(dbcode);
					    List<Map<String, Object>> list = studentBaseService.findStudentAnswerTestService(paramsMap);
			            response.setReturnMsg(1, "操作成功");
			            response.setListData(list);
						return response.toJSON();
			            
					} catch (Exception e) {
						logger.error("findCompany" + e.toString());
						response.setReturnCode(1);
						response.setReturnMsg("查询失败");
						response.setReturnException(e.toString());
					} finally {
						HandlerDataSource.clear();
						return response.toJSON();
					}
				}
				
				//查询考试
				@SuppressWarnings("finally")
				@RequestMapping(value = "/findStudentBaseToProfession", method = { RequestMethod.GET,
						RequestMethod.POST }, produces = "application/json; charset=utf-8")
				public @ResponseBody String findStudentBaseToProfession(HttpServletRequest request) throws UnsupportedEncodingException {

					RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
					request.setCharacterEncoding("UTF-8");
					try {
						String info = request.getParameter("info");
						System.out.println("info"+info);
						Map<String,Object> paramsMap = Tools.JsonToMap(info);
						String dbcode = paramsMap.get("dbcode").toString();
						//设置数据源
						HandlerDataSource.setDataSource(dbcode);
						PageBean pageBean = studentBaseService.findStudentBaseToProfessionService(paramsMap);
						response.setReturnMsg(1, "操作成功");
			            response.setTotalCount(pageBean.getAllRow());
			            response.setTotalPage(pageBean.getTotalPage());
						response.setListData(pageBean.getList());
			            
					} catch (Exception e) {
						logger.error("findCompany" + e.toString());
						response.setReturnCode(1);
						response.setReturnMsg("查询失败");
						response.setReturnException(e.toString());
					} finally {
						HandlerDataSource.clear();
						return response.toJSON();
					}
				}
				
		   //学员补考修改学员信息表中学员状态
            @SuppressWarnings("finally")
			@RequestMapping(value = "/updateStudentBaseExamStatus", method = { RequestMethod.GET,
					RequestMethod.POST }, produces = "application/json; charset=utf-8")
			public @ResponseBody String updateStudentBaseExamStatus(HttpServletRequest request) throws UnsupportedEncodingException {
				
				RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
				try{
					String info = request.getParameter("info");
					System.out.println("info"+info);
					Map<String,Object> paramsMap = Tools.JsonToMap(info);
					System.out.println("paramsMap"+paramsMap);
					String ids = paramsMap.get("ids").toString();
					String[] idarray = ids.split(",");
					paramsMap.put("idarray", idarray);
					String dbcode = paramsMap.get("dbcode").toString();
				    //设置数据源
					HandlerDataSource.setDataSource(dbcode);
					int ret = studentBaseService.updateStudentBaseExamStatusService(paramsMap);
					if(ret>0) {
						response.setReturnMsg(1, "更新成功");
						return response.toJSON();
					}
					else{
					    response.setReturnMsg(0, "更新失败");
					    return response.toJSON();
					}
					
				} catch (Exception e) {
					logger.error("删除异常" + e.toString());
					// 异常信息
					response.setReturnCode(0);
					response.setReturnMsg("操作失败");
					response.setReturnException(e.toString());
					e.printStackTrace();
				}
				
				finally {
					HandlerDataSource.clear();
					return response.toJSON();
				}
				
			}
            
          //查询考试
			@SuppressWarnings("finally")
			@RequestMapping(value = "/findStudentBaseToProfessionExam", method = { RequestMethod.GET,
					RequestMethod.POST }, produces = "application/json; charset=utf-8")
			public @ResponseBody String findStudentBaseToProfessionExam(HttpServletRequest request) throws UnsupportedEncodingException {

				RestResponse response = new RestResponse(Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
				request.setCharacterEncoding("UTF-8");
				try {
					String info = request.getParameter("info");
					System.out.println("info"+info);
					Map<String,Object> paramsMap = Tools.JsonToMap(info);
					String dbcode = paramsMap.get("dbcode").toString();
					//设置数据源
					HandlerDataSource.setDataSource(dbcode);
					PageBean pageBean = studentBaseService.findStudentBaseToProfessionExamService(paramsMap);
					response.setReturnMsg(1, "操作成功");
		            response.setTotalCount(pageBean.getAllRow());
		            response.setTotalPage(pageBean.getTotalPage());
					response.setListData(pageBean.getList());
		            
				} catch (Exception e) {
					logger.error("findCompany" + e.toString());
					response.setReturnCode(1);
					response.setReturnMsg("查询失败");
					response.setReturnException(e.toString());
				} finally {
					HandlerDataSource.clear();
					return response.toJSON();
				}
			}
			
			/**
			 * 轮训
			 * 
			 * @param request
			 * @return
			 * @throws UnsupportedEncodingException
			 */
			@SuppressWarnings("finally")
			@RequestMapping(value = "/addRotationTraining", method = { RequestMethod.GET,
					RequestMethod.POST }, produces = "application/json; charset=utf-8")
			public @ResponseBody String addRotationTraining(HttpServletRequest request) throws UnsupportedEncodingException {
				request.setCharacterEncoding("UTF-8");
				Map<String,Object> resultMap = new HashMap<>();
				try {
					String checkParameter= request.getParameter("info");
					Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
					String dbcode = paramsMap.get("dbcode").toString();
					HandlerDataSource.setDataSource(dbcode);
					resultMap = studentBaseService.addRotationTraining(paramsMap);
					resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
				} catch (Exception e) {
					logger.info("addRotationTraining" + e.toString());
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "轮训失败");
				} finally {
					HandlerDataSource.clear();
					return JSON.toJSONString(resultMap);
				}
				
			}	
			
			/**
			 * 根据 [IdCard]判断学员是否存在
			 * 
			 * @param request
			 * @return
			 * @throws UnsupportedEncodingException
			 */
			@SuppressWarnings("finally")
			@RequestMapping(value = "/checkIsHaveStudent", method = { RequestMethod.GET,
					RequestMethod.POST }, produces = "application/json; charset=utf-8")
			public @ResponseBody String checkIsHaveStudent(HttpServletRequest request) throws UnsupportedEncodingException {
				request.setCharacterEncoding("UTF-8");
				Map<String,Object> resultMap = new HashMap<>();
				try {
					String checkParameter= request.getParameter("info");
					Map<String,Object> paramsMap = Tools.JsonToMap(checkParameter);
					String dbcode = paramsMap.get("dbcode").toString();
					HandlerDataSource.setDataSource(dbcode);
					resultMap = studentBaseService.checkIsHaveStudent(paramsMap);
					resultMap.put("pubKey",Optional.ofNullable(request.getAttribute("pubKey")).orElse(""));
				} catch (Exception e) {
					logger.info("checkIsHaveStudent" + e.toString());
					resultMap.put("returnCode", 0);
					resultMap.put("returnMsg", "检查失败");
				} finally {
					HandlerDataSource.clear();
					return JSON.toJSONString(resultMap);
				}
				
			}		
		
}
